<template>
    <div class="box">
        <header class="top">
            <p>购物车</p>
            <van-button @click="deleteAll">
                <template #icon>
                    <span class="iconfont icon-shanchu"></span>
                </template>
            </van-button>
        </header>
        <main class="main">
            <div class="cart-item" v-for="item in cartArr" :key="item.cartId">
                <van-checkbox v-model="item.checked"></van-checkbox>
                <van-swipe-cell>
                    <van-card v-bind:desc="item.food.foodExplain" :title="item.food.foodName" class="goods-card"
                        :thumb="item.food.foodImg">
                        <template #price> ￥:{{ item.food.foodPrice }}.00 </template>
                        <template #num>
                            <van-stepper v-model="item.quantity" theme="round" button-size="22" disable-input
                                @plus="plus(item.cartId, item.quantity + 1)"
                                @minus="minus(item.cartId, item.quantity - 1)" />
                        </template>
                    </van-card>
                    <template #right>
                        <van-button square text="删除" type="danger" class="delete-button"
                            @click="deleteCart(item.cartId)" />
                    </template>
                </van-swipe-cell>
            </div>
        </main>
        <footer class="footer">
            <van-action-bar>
                <van-action-bar-icon>
                    <template #icon>
                        <span class="iconfont icon-elemo"></span>
                    </template>
                    <template #default>
                        金额：<span style="font-size: 20px; color: #a00">￥{{ totalMoney }}.00</span>
                    </template>
                </van-action-bar-icon>
                <van-action-bar-button color="#7232dd" type="danger" text="立即下单"
                    @click="$router.push('/orderConfirm')" />
            </van-action-bar>
            <van-tabbar router v-model="currentPage">
                <van-tabbar-item name="home" icon="home-o" to="/">首页</van-tabbar-item>
                <van-tabbar-item icon="cart-circle">超市</van-tabbar-item>
                <van-tabbar-item icon="comment-o">信息</van-tabbar-item>
                <van-tabbar-item name="cart" icon="shopping-cart-o" to="/cart">
                    购物车
                </van-tabbar-item>
                <van-tabbar-item icon="user-o">我的</van-tabbar-item>
            </van-tabbar>
        </footer>
    </div>
</template>

<script>
import { getCartDataAPI, deleteCartByIdsAPI, updateCartByIdAPI } from "@/api/cart";
export default {
    data() {
        return {
            // 表单当前切换的页面
            currentPage: "cart",
            checked: false,
            value: 2,
            loginUser: {},
            // 定义数组，存储购物车数据
            cartArr: []
        };
    },
    // 通过计算属性去处理购物车总金额
    computed: {
        totalMoney() {
            let sum = 0;
            for (let i = 0; i < this.cartArr.length; i++) {
                if (this.cartArr[i].checked) {
                    sum += this.cartArr[i].food.foodPrice * this.cartArr[i].quantity;
                }
            }
            return sum;
        },
    },
    methods: {
        // 加载当前用户的购物车数据
        loadCardData() {
            getCartDataAPI({ userId: this.loginUser.userId }).then((resp) => {
                if (resp.data.code == 20000) {
                    this.cartArr = resp.data.datas.map((item) => {
                        return { ...item, checked: false };
                    });
                }
            });
        },
        // 点击购物车页面定义的删除按钮
        deleteAll() {
            // 获取选中的所有待删除的购物车中的菜品的id
            let ids = [];
            for (let i = 0; i < this.cartArr.length; i++) {
                if (this.cartArr[i].checked) {
                    ids.push(this.cartArr[i].cartId);
                }
            }
            // 判断是否有选中的购物车中的菜品
            if (ids.length > 0) {
                deleteCartByIdsAPI(ids).then((resp) => {
                    if (resp.data.code == 20000) {
                        showNotify({
                            type: "success",
                            message: resp.data.message,
                        });
                        this.loadCardData();
                    }
                });
            } else {
                showNotify({
                    type: "danger",
                    message: "请选择要删除的购物车中的菜品",
                });
            }
        },
        // 购物车单独上传删除购物车中的菜品
        deleteCart(cartId) {
            // 这里借助批量删除的功能，不需要再单独书写对应的接口
            deleteCartByIdsAPI([cartId]).then((resp) => {
                if (resp.data.code == 20000) {
                    showNotify({
                        type: "success",
                        message: resp.data.message,
                    });
                    this.loadCardData();
                }
            });
        },
        // 购物车数据修改
        plus(cartId, quantity) {
            updateCartByIdAPI({ cartId, quantity }).then((resp) => {
                if (resp.data.code == 20000) {
                    showNotify({
                        type: "success",
                        message: resp.data.message,
                    });
                    this.loadCardData();
                }
            });
        },
        minus(cartId, quantity) {
            this.plus(cartId, quantity);
        }
    },
    created() {
        let loginUser = localStorage.getItem("loginUser");
        if (!loginUser) {
            this.$router.push("/login");
            return;
        }
        this.loginUser = JSON.parse(loginUser);
        this.loadCardData();
    }
};
</script>

<style lang="less" scoped>
.box {
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;

    .top {
        display: flex;
        align-items: center;
        font-size: 20px;
        height: 44px;

        p {
            flex: 1;
            text-align: center;
        }
    }

    .main {
        flex: 1;
        background-color: #eee;

        .cart-item {
            display: flex;
            align-items: center;
            margin-top: 5px;

            .van-swipe-cell {
                flex: 1;
            }
        }

        .goods-card {
            margin: 0;
            background-color: #fff;
        }

        .delete-button {
            height: 100%;
        }
    }

    .footer {
        height: 100px;

        .van-action-bar {
            bottom: 49px;
        }
    }
}
</style>
